<?php
/**
 * Created by PhpStorm.
 * User: poptser
 * Email: poptser@foxmail.com
 * Date: 2016/8/19
 * Time: 19:37
 */

namespace YMApi\Controller;
use Com\Alipay\AlipayNotify;
use Think\Controller;
use Think\Log;
class AlipaynotifyController extends Controller
{
    private function get_config($pay_id){
        //return $this->where(array("pay_id"=>$pay_id,"enabled"=>1))->getField("pay_config");
        $array = array(
            'seller_id' => '2088811720960505',                                          //合作身份者ID
            'partner' => '2088811720960505',                                            //合作身份者ID
            'key' => 'cgfk1p3u0dngsghykks56rezaxqsbkpu',                                //KEY
            'transport' => 'http',
            'payment_type' => '1',
            'service' => 'alipay.wap.create.direct.pay.by.user',
            'sign_type' => strtoupper('MD5'),
            'input_charset' => strtolower('utf-8')
        );
        return $array;
    }
    
    private function get_app_config(){
    	$ROOT =  str_replace('\\','/',realpath(dirname(__FILE__).'/../../').'/');
    	//支付宝app支付2.0接口参数设置，留着备用
//     	$array = array(
//     			'app_id'=>'2016062801559463',
//     			'method'=>'alipay.trade.app.pay',
//     			'charset'=>strtolower('utf-8'),
//     			'sign_type' => strtoupper('RSA'),
//     			'version'=>'1.0',
//     			'seller_id'=>'2088811720960505',
//     			'product_code'=>'QUICK_MSECURITY_PAY',
//     			'key' => 'cgfk1p3u0dngsghykks56rezaxqsbkpu',
//     			'private_key_path'=>$ROOT.'api/key/rsa_private_key.pem',
//     			'ali_public_key_path'=>$ROOT.'api/key/alipay_rsa_public_key.pem'
//     	);
		$array = array(
				'seller_id' => 'admin@shidexian.com',                                          //合作身份者ID
				'partner' => '2088811720960505',                                            //合作身份者ID
				'key' => 'cgfk1p3u0dngsghykks56rezaxqsbkpu',                                //KEY
				'transport' => 'http',
				'payment_type' => '1',
				'service' => 'mobile.securitypay.pay',
				'sign_type' => strtoupper('RSA'),
				'input_charset' => strtolower('utf-8'),
				'private_key_path'=>$ROOT.'api/key_old/rsa_private_key.pem',
				'ali_public_key_path'=>$ROOT.'api/key_old/alipay_rsa_public_key.pem'
		);
    	 
    	return $array;
    }
    /**
     *支付宝异步判断支付结果
     */
    public function alipay_notifypay(){
        set_time_limit(0);
    	$config = $this->get_app_config();
    	if($_POST['sign_type'] && $_POST['sign_type']!=$config['sign_type']){
    		$config = $this->get_config();
    	}
    	$alipayNotify = new AlipayNotify($config);
        $verify_result = $alipayNotify->verifyNotify();
        if($verify_result) {//验证成功
            $out_trade_no = $_POST['out_trade_no'];//商户订单号
            $trade_no = $_POST['trade_no'];//支付宝交易号
            $trade_status = $_POST['trade_status'];//交易状态

            if($_POST['trade_status'] == 'TRADE_FINISHED'||$_POST['trade_status'] == 'TRADE_SUCCESS') {
                $out_trade_db = explode("s",$out_trade_no);
                if($out_trade_db[1] == PAY_SURPLUS){
                    //充值回调修改
                    $update = D('Payment')->updata_recharg_log($out_trade_db[0]);    //更新支付状态
                    if($update){
                    	$_POST['out_trade_no'] = $out_trade_db[0];
                    	D('Payment')->update_alipay_log($_POST,PAY_SURPLUS);
                        echo "success";
                    }else{
                        echo "fail";
                    }

                }elseif($out_trade_db[1] == PAY_ORDER){
                    $pay_order = D('Payment')->get_pay_log($out_trade_db[0],$out_trade_db[1]);
                    
                    if($_POST["total_fee"]<$pay_order["order_amount"]){
                        $surplus['user_id'] = $pay_order['user_id'];
                        $surplus['amount'] = $_POST["total_fee"];
                        $surplus['process_type'] = 0;
                        $surplus['user_note'] = 0;
                        $surplus['payment'] = '支付宝';
                        $surplus['admin_note'] = '混合支付';
                        $log_id = D("Payment")->add_recharge_log($surplus,$_POST["total_fee"]);
                        
                        $update = D('Payment')->updata_recharg_log($log_id);    //更新支付状态
                        
                        if($update){
                            $_POST['out_trade_no'] = $log_id;
                            D('Payment')->update_alipay_log($_POST,PAY_SURPLUS);
                            D("Payment")->tobalance_pay($out_trade_db[0]);
                            
                            echo "success";
                        }else{
                            echo "fail";
                        }
               
                    
                    }else{
                        $update = D('Payment')->order_paid($out_trade_db[0]);    //更新支付状态
                        //订单支付
                        if($update['pay_success']){
                            $_POST['out_trade_no'] = $out_trade_db[0];
                            D('Payment')->update_alipay_log($_POST,PAY_ORDER);
                            echo "success";
                        }else{
                            echo "fail";
                        }
                    }
                  
                    
                }
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
//             echo "success";		//请不要修改或删除
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }
        else {
            //验证失败
            echo "fail";
            //调试用，写文本函数记录程序运行情况是否正常
            //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
        }
    }
    
    public function write_log($message,$filename){
    	$log = new Log();
    	$destination = C('LOG_PATH').date('y_m_d').'_'.$filename.'.log';
    
    	$log->write($message,'DEBUG','',$destination);
    }
}